package com.dstation.jobhandle;

import com.dstation.domain.CoinOperatedInfo;
import com.dstation.domain.CollectionInfo;
import com.dstation.domain.HistoryInfo;
import com.dstation.domain.VideoLikedInfo;
import com.dstation.service.interf.IRecommendService;
import com.dstation.utils.RecommendStrategyUtil;
import com.dstation.utils.RedisPreKey;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Component
@Slf4j
public class HotDataRecommendJob {

    static String REGEX_SPACE = "\r|\n";//定义空格回车换行符
    static Pattern P_SPACE = Pattern.compile(REGEX_SPACE, Pattern.CASE_INSENSITIVE);


    @Resource
    private IRecommendService recommendService;


    @Resource
    private JedisPool redisPoolFactory;



    @XxlJob("findHotDataJob")
    private ReturnT<String> findHotDataJob(String param) throws Exception{
        XxlJobLogger.log("开始---->推荐  热门数据部分 {}", param);

        //获取一个月内的热门数据
        int n=100;
        //获取具有时效性的热门数据
        Timestamp  deadLine=new Timestamp(System.currentTimeMillis()- 86400000 * n);

        //浏览数据  25
        List<HistoryInfo> browserList=recommendService.findHotBrowser(deadLine);
        //点赞数据  25
        List<VideoLikedInfo> likedInfoList=recommendService.findHotLiked(deadLine);
        //收藏数据   25
        List<CollectionInfo> collectionInfoList=recommendService.findHotCollection(deadLine);
        //投币数据  25
        List<CoinOperatedInfo> coinOperatedInfoList=recommendService.findHotCoin(deadLine);

        Jedis jedis = redisPoolFactory.getResource();
        Pipeline pipline = jedis.pipelined();
        Map<String, Double> map = new HashMap();



        int size= RecommendStrategyUtil.HOT_DATA_SIZE/4;
        for(int i=0;i<size;i++){
            if(i+1<=browserList.size()){
                map.put(String.valueOf(browserList.get(i).getVideoId()),(double)i);
            }

            if(i+1<=likedInfoList.size()){
                map.put(String.valueOf(likedInfoList.get(i).getVideoId()),(double)i);
            }

            if(i+1<=collectionInfoList.size()){
                map.put(String.valueOf(collectionInfoList.get(i).getVideoId()),(double)i);
            }
            if(i+1<=coinOperatedInfoList.size()){
                map.put(String.valueOf(coinOperatedInfoList.get(i).getVideoId()),(double)i);
            }
        }
        pipline.zadd(RedisPreKey.HOT_RECOMMEND_DATA, map);


        pipline.sync();

        XxlJobLogger.log("结束---->推荐  热门数据部分完成 {}", param);

        return ReturnT.SUCCESS;
    }
}
